package com.kchouse.homepage;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.model.LatLng;
import com.kchouse.MainActivity;
import com.kchouse.StartActivity;
import com.kchouse.bean.BannerItem;
import com.kchouse.bean.BrandItem;
import com.kchouse.bean.DirItem;
import com.kchouse.bean.MerchantItem;
import com.kchouse.bean.ProjectList;
import com.kchouse.bean.SeriesItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.R;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.MyUtils;
import com.kchouse.myadapter.UnionAdapter;
import com.kchouse.union.MerchantDetailsActivity;
import com.kchouse.view.BannerLoader;
import com.kchouse.common.ToastUtils;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

public class DirectlyActivity extends BaseActivity implements View.OnClickListener {

    private DirectlyActivity mContent;
    private ListView lv_item;
    private ListView lv_sbitem;
    private ImageView iv_back;
    private ArrayList<BannerItem> listbanner = new ArrayList<>();
    private ArrayList<BrandItem> listbrand = new ArrayList<>();
    private ArrayList<SeriesItem> listseries = new ArrayList<>();
    private ArrayList<MerchantItem> listmerchant = new ArrayList<>();

    private ArrayList<DirItem> listdir = new ArrayList();
    private ArrayList<String> listchidtype = new ArrayList();//子分类
    private View ll_directly_1;
    private View ll_directly_2;
    private View ll_directly_3;
    private View ll_directly_4;
    private View ll_directly_5;
    private View ll_directly_6;
    private View ll_directly_7;
    private View ll_directly_8;
    private ImageView iv_directly_1;
    private ImageView iv_directly_2;
    private ImageView iv_directly_3;
    private ImageView iv_directly_4;
    private ImageView iv_directly_5;
    private ImageView iv_directly_6;
    private ImageView iv_directly_7;
    private ImageView iv_directly_8;
    private ScrollView sv_item;
    private TextView tv_title;
    private ArrayList<Integer> listimg = new ArrayList();
    private ArrayList<Integer> listdirimg8 = new ArrayList();
    private LvAdapter adapter;
    private EditText et_search;
    private HorizontalScrollView hsv_item;
    private RadioGroup rg_item;

    HashMap<Integer, String> hsdir = new HashMap<>();
    private View ll_servicebusinesses;
    private View ll_item;
    private TextView tv_cartpye;
    private ListView lv_dialogitem;
    private ListView lv_dialogitem2;
    private AlertDialog myDialog;
    private int page = 1;
    private LvSbAdapter sbadapter;
    private Integer totalCount;
    private TextView tv_addpage;
    private String suitType;
    private Intent intent;
    private View rl_search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_directly);

        mContent = this;
        addAct(mContent);
        intiData();
        intiView();
    }


    /**
     * 获取商家列表
     * suitType： MAINTAIN 保养套餐 YEAR 全年套餐 CAR全车喷漆 GLASS 玻璃贴膜 CRYSTAL 镀晶套餐 ONE 一元洗车 LACQUER 漆面贴膜
     */
    private void GetMerchantList(String name, String suitType, int page) {
        String url = API.GeterviceList;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数

        params.addFormDataPart("name", name);
        params.addFormDataPart("suitType", suitType);
        params.addFormDataPart("publishType", "UNION");
        params.addFormDataPart("page", page);
        params.addFormDataPart("pageSize", 10);
        params.addFormDataPart("lat", StartActivity.mLatitude + "");
        params.addFormDataPart("log", StartActivity.mLongitude + "");
        params.addFormDataPart("userId", MainActivity.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    totalCount = data.getInteger("totalCount");
                    if (listmerchant.size() == totalCount)//总个数已满
                    {
//                        hao_recycleview.setCanloadMore(false);
                        ToastUtils.getInstanc(mContent).showToast("暂无更多");
                        tv_addpage.setVisibility(View.GONE);
                    } else {
                        listmerchant.addAll(JSONObject.parseArray(data.getString("merchantList"), MerchantItem.class));
                    }
                    sbadapter.notifyDataSetChanged();
                    if (JSONObject.parseArray(data.getString("merchantList"), MerchantItem.class).size() == 0) {
                        ToastUtils.getInstanc(mContent).showToast("暂无更多");
                        tv_addpage.setVisibility(View.GONE);
                    }

                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    private void intiView() {

        sv_item = (ScrollView) findViewById(R.id.sv_item);
        hsv_item = (HorizontalScrollView) findViewById(R.id.hsv_item);
        ll_item = findViewById(R.id.ll_item);
        tv_cartpye = (TextView) findViewById(R.id.tv_cartpye);
        tv_cartpye.setOnClickListener(this);
        ll_servicebusinesses = findViewById(R.id.ll_servicebusinesses);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("平台直营");
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);
        tv_addpage = (TextView) findViewById(R.id.tv_addpage);
        tv_addpage.setOnClickListener(this);

        lv_item = (ListView) findViewById(R.id.lv_item);
        lv_item.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                intent.putExtra("isDir", true);
                intent.putExtra("id", listdir.get(position).getId());
                intent.setClass(mContent, GoodsDetailsActivity.class);
                startActivity(intent);
            }
        });
        adapter = new LvAdapter();
        lv_item.setAdapter(adapter);
        lv_sbitem = (ListView) findViewById(R.id.lv_sbitem);
        sbadapter = new LvSbAdapter();
        lv_sbitem.setAdapter(sbadapter);
        lv_sbitem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MerchantItem item = listmerchant.get(position);
//                ToastUtils.getInstanc(mContent).showToast("商家id："+item.getId());

                intent.putExtra("Merchantid", item.getId());
                intent.setClass(mContent, MerchantDetailsActivity.class);
                startActivity(intent);
            }
        });
        et_search = (EditText) findViewById(R.id.et_search);
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//                    ToastUtils.getInstanc(mContent).showToast("搜索");
                    if (!TextUtils.isEmpty(et_search.getText().toString())) {
                        page = 1;
                        listmerchant.clear();
                        GetMerchantList(et_search.getText().toString(), suitType, page);
                        tv_addpage.setVisibility(View.GONE);
                        et_search.setText("");
                    }
                }
                return false;
            }
        });

        rl_search = findViewById(R.id.rl_search);
        rl_search.setOnClickListener(this);
        intidirectly();

        intiBanner();

        rg_item = (RadioGroup) findViewById(R.id.rg_item);
        rg_item.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                if (checkedId == group.getCheckedRadioButtonId()) {
                    Log.e("===", listchidtype.get(checkedId));
                    switch (listchidtype.get(checkedId)) {
                        case "ONE"://单次
                            GetDirList(suitType, "ONE", false);
                            break;
                        case "TWO"://两次
                            GetDirList(suitType, "TWO", false);
                            break;
                        case "THREE"://买三送一
                            GetDirList(suitType, "THREE", false);
                            break;
                        case "FIVE"://买五送二
                            GetDirList(suitType, "FIVE", false);
                            break;
                    }
                }


            }
        });

    }

    @SuppressLint("ResourceType")
    private void addrb() {

        String childType = null;
        for (int i = 0; i < listdir.size(); i++) {

            RadioButton radioButton = new RadioButton(this);
            radioButton.setId(i);
//            if (i == hs.size()) {
//                radioButton.setChecked(true);
//            }
            RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(12, 0, 0, 0);
            radioButton.setLayoutParams(layoutParams);
            radioButton.setText(listdir.get(i).getChildTypeName());
            radioButton.setTextSize(13);
            radioButton.setButtonDrawable(android.R.color.transparent);//隐藏单选圆形按钮
            radioButton.setGravity(Gravity.CENTER);
            radioButton.setPadding(12, 8, 12, 8);
            radioButton.setTextColor(getResources().getColorStateList(R.drawable.checked_item_color));//设置选中/未选中的文字颜色
            radioButton.setBackground(getResources().getDrawable(R.drawable.rb_item_background));//设置按钮选中/未选中的背景
            rg_item.addView(radioButton, rg_item.getChildCount() - 1, layoutParams);//将单选按钮添加到RadioGroup中
        }
    }


    /**
     * 初始化套餐控件
     */
    private void intidirectly() {
        ll_directly_1 = findViewById(R.id.ll_directly_1);
        ll_directly_1.setOnClickListener(this);
        ll_directly_2 = findViewById(R.id.ll_directly_2);
        ll_directly_2.setOnClickListener(this);
        ll_directly_3 = findViewById(R.id.ll_directly_3);
        ll_directly_3.setOnClickListener(this);
        ll_directly_4 = findViewById(R.id.ll_directly_4);
        ll_directly_4.setOnClickListener(this);
        ll_directly_5 = findViewById(R.id.ll_directly_5);
        ll_directly_5.setOnClickListener(this);
        ll_directly_6 = findViewById(R.id.ll_directly_6);
        ll_directly_6.setOnClickListener(this);
        ll_directly_7 = findViewById(R.id.ll_directly_7);
        ll_directly_7.setOnClickListener(this);
        ll_directly_8 = findViewById(R.id.ll_directly_8);
        ll_directly_8.setOnClickListener(this);
        iv_directly_1 = (ImageView) findViewById(R.id.iv_directly_1);
        iv_directly_2 = (ImageView) findViewById(R.id.iv_directly_2);
        iv_directly_3 = (ImageView) findViewById(R.id.iv_directly_3);
        iv_directly_4 = (ImageView) findViewById(R.id.iv_directly_4);
        iv_directly_5 = (ImageView) findViewById(R.id.iv_directly_5);
        iv_directly_6 = (ImageView) findViewById(R.id.iv_directly_6);
        iv_directly_7 = (ImageView) findViewById(R.id.iv_directly_7);
        iv_directly_8 = (ImageView) findViewById(R.id.iv_directly_8);

        iv_directly_1.setImageResource(R.mipmap.ic_directly_1_on);//默认第一个选中


    }


    /**
     * 初始化首页banner
     */
    private void intiBanner() {
        Banner banner = (Banner) findViewById(R.id.banner);
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new BannerLoader());
        //设置图片集合
        banner.setImages(listbanner);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
    }

    private void intiData() {

        intent = getIntent();

        GetBanner("UNION");

        //第一次初始化商家（保养套餐）
        suitType = "MAINTAIN";
        GetMerchantList("", suitType, page);
        GetDirList(suitType, null, true);


    }


    private void GetDirList(String suitType, String chidtype, final Boolean isadd) {
        String url = API.GetDirList;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数

        params.addFormDataPart("type", suitType);
        params.addFormDataPart("childType", chidtype);
        params.addFormDataPart("publishType", "UNION");

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    listdir.clear();
                    listdir.addAll(JSONObject.parseArray(data.getString("suitList"), DirItem.class));
                    if (isadd) {
                        isaddrb();
                    }
                    adapter.notifyDataSetChanged();
//                    listmerchant.addAll(JSONObject.parseArray(data.getString("suitList"), MerchantItem.class));
//                    sbadapter.notifyDataSetChanged();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    /**
     * 是否添加RadioButton
     */
    private void isaddrb() {
        listchidtype.clear();
        for (int i = 0; i < listdir.size(); i++) {
            DirItem item = listdir.get(i);
            if (!listchidtype.contains(item.getChildType())) {
                listchidtype.add(item.getChildType());
            }
        }
        addrb();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                delAct(mContent);
                finish();
                break;
            case R.id.ll_directly_1:

                closeImage();
                hsv_item.setVisibility(View.VISIBLE);
//                addrb(hsdir1, 100);
                iv_directly_1.setImageResource(R.mipmap.ic_directly_1_on);
//                listimg.addAll(listdirimg1);
//                adapter.notifyDataSetChanged();

                //初始化商家（保养套餐）
                listmerchant.clear();
                page = 1;
                tv_addpage.setVisibility(View.VISIBLE);
                suitType = "MAINTAIN";
                GetMerchantList("", suitType, page);
                GetDirList(suitType, null, true);
                ll_servicebusinesses.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_directly_2:
                closeImage();
                iv_directly_2.setImageResource(R.mipmap.ic_directly_2_on);
//                listimg.addAll(listdirimg2);
//                adapter.notifyDataSetChanged();
                //初始化商家（全年套餐）
                listmerchant.clear();
                page = 1;
                tv_addpage.setVisibility(View.VISIBLE);
                suitType = "YEAR";
                GetMerchantList("", suitType, page);
                GetDirList(suitType, null, true);
                ll_servicebusinesses.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_directly_3:
                closeImage();
                ll_item.setVisibility(View.VISIBLE);
                iv_directly_3.setImageResource(R.mipmap.ic_directly_3_on);
                //初始化商家（全车喷漆）
                listmerchant.clear();
                page = 1;
                tv_addpage.setVisibility(View.VISIBLE);
                suitType = "CAR";
                GetMerchantList("", suitType, page);
                GetDirList(suitType, null, true);
                adapter.notifyDataSetChanged();
                ll_servicebusinesses.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_directly_4:
                closeImage();
                hsv_item.setVisibility(View.VISIBLE);
                iv_directly_4.setImageResource(R.mipmap.ic_directly_4_on);
                listmerchant.clear();
                page = 1;
                tv_addpage.setVisibility(View.VISIBLE);
                suitType = "LACQUER";
                GetMerchantList("", suitType, page);
                GetDirList(suitType, null, true);
                adapter.notifyDataSetChanged();
                ll_servicebusinesses.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_directly_5:
                closeImage();
                hsv_item.setVisibility(View.VISIBLE);
//                addrb(hsdir5, 500);
                iv_directly_5.setImageResource(R.mipmap.ic_directly_5_on);
                listmerchant.clear();
                page = 1;
                tv_addpage.setVisibility(View.VISIBLE);
                suitType = "GLASS";
                GetMerchantList("", suitType, page);
                GetDirList(suitType, null, true);
                adapter.notifyDataSetChanged();
                ll_servicebusinesses.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_directly_6:
                closeImage();
                iv_directly_6.setImageResource(R.mipmap.ic_directly_6_on);
                listmerchant.clear();
                page = 1;
                tv_addpage.setVisibility(View.VISIBLE);
                suitType = "CRYSTAL";
                GetMerchantList("", suitType, page);
                GetDirList(suitType, null, true);
                ll_servicebusinesses.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_directly_7:
                closeImage();
                iv_directly_7.setImageResource(R.mipmap.ic_directly_7_on);
                listmerchant.clear();

                page = 1;
                tv_addpage.setVisibility(View.VISIBLE);
                suitType = "ONE";
                GetMerchantList("", suitType, page);
                GetDirList(suitType, null, true);
                adapter.notifyDataSetChanged();
                ll_servicebusinesses.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_directly_8:
                closeImage();
                hsv_item.setVisibility(View.VISIBLE);
//                addrb(hsdir7, 700);
                iv_directly_8.setImageResource(R.mipmap.ic_directly_8_on);
                listimg.addAll(listdirimg8);
                listdir.clear();
                listmerchant.clear();
//                adapter.notifyDataSetChanged();
                ll_servicebusinesses.setVisibility(View.GONE);
                break;
            case R.id.tv_cartpye://筛选喷漆套餐
                getcarbrand();
                break;
            case R.id.tv_addpage:
                page = page + 1;
                GetMerchantList("", suitType, page);
                break;
            case R.id.rl_search:

                break;
        }
//        sv_item.scrollTo(0, 0);
    }

    /**
     * 获取汽车品牌
     */
    private void getcarbrand() {
        String url = API.GetBrandList;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    listbrand.clear();
                    listbrand.addAll(JSONObject.parseArray(json.getString("data"), BrandItem.class));
                    showcartype(listbrand);
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    /**
     * 获取汽车品牌系列车型
     */
    private void getcarseries(String id, final int carbrandindex) {
        String url = API.GeteriesList + id;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addFormDataPart("id", id);//表单数据
        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    listseries.clear();
                    listseries.addAll(JSONObject.parseArray(json.getString("data"), SeriesItem.class));

                    lv_dialogitem.setVisibility(View.GONE);
                    lv_dialogitem2.setVisibility(View.VISIBLE);
//
                    CartpyeAdapter2 cartpyeadapter2 = new CartpyeAdapter2(listseries);
                    lv_dialogitem2.setAdapter(cartpyeadapter2);
                    lv_dialogitem2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            ToastUtils.getInstanc(mContent).showToast(listbrand.get(carbrandindex).getName()
                                    + listseries.get(position).getName());
                            myDialog.dismiss();

                            //TODO 开始搜索


                        }
                    });
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    /**
     * 显示对话框选择车型
     */
    private void showcartype(final ArrayList<BrandItem> list) {
        myDialog = new AlertDialog.Builder(mContent).create();
        myDialog.show();
        myDialog.getWindow().setContentView(R.layout.lay_listview);
        lv_dialogitem = (ListView) myDialog.getWindow().findViewById(R.id.lv_item);
        lv_dialogitem2 = (ListView) myDialog.getWindow().findViewById(R.id.lv_item2);
//        final String car_description_list[] = mContent.getResources()
//                .getStringArray(R.array.car_description_list);
        CartpyeAdapter cartpyeadapter = new CartpyeAdapter(list);
        lv_dialogitem.setAdapter(cartpyeadapter);
        lv_dialogitem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                getcarseries(listbrand.get(position).getId(), position);
            }
        });
    }


    /**
     * 车品牌适配器
     */
    class CartpyeAdapter extends BaseAdapter {
        private ArrayList<BrandItem> list;

        public CartpyeAdapter(ArrayList<BrandItem> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View view = getLayoutInflater().inflate(android.R.layout.simple_list_item_1, null);
            TextView text1 = (TextView) view.findViewById(android.R.id.text1);
            text1.setText(list.get(position).getName());
            return view;
        }
    }


    class CartpyeAdapter2 extends BaseAdapter {
        private ArrayList<SeriesItem> list;

        public CartpyeAdapter2(ArrayList<SeriesItem> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View view = getLayoutInflater().inflate(android.R.layout.simple_list_item_1, null);
            TextView text1 = (TextView) view.findViewById(android.R.id.text1);
            text1.setText(list.get(position).getName());
            return view;
        }
    }

    /**
     * 关闭所有图标
     */
    private void closeImage() {
        iv_directly_1.setImageResource(R.mipmap.ic_directly_1_off);
        iv_directly_2.setImageResource(R.mipmap.ic_directly_2_off);
        iv_directly_3.setImageResource(R.mipmap.ic_directly_3_off);
        iv_directly_4.setImageResource(R.mipmap.ic_directly_4_off);
        iv_directly_5.setImageResource(R.mipmap.ic_directly_5_off);
        iv_directly_6.setImageResource(R.mipmap.ic_directly_6_off);
        iv_directly_7.setImageResource(R.mipmap.ic_directly_7_off);
        iv_directly_8.setImageResource(R.mipmap.ic_directly_8_off);
        listimg.clear();
        hsv_item.setVisibility(View.GONE);
        ll_item.setVisibility(View.GONE);
        rg_item.removeAllViews();
        hsdir.clear();
    }


    /**
     * 直营
     */
    class LvAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return listdir.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            DirItem item = listdir.get(position);

            View view = getLayoutInflater().inflate(R.layout.lv_directly_item, null);
            TextView tv_original = (TextView) view.findViewById(R.id.tv_original);
            tv_original.setText(MyUtils.getdouble(item.getOriginalPrice()));

            tv_original.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//添加下划线
            ImageView iv_item = (ImageView) view.findViewById(R.id.iv_item);
            Picasso.with(mContent).load(item.getUrl()).error(R.mipmap.ic_loadingerror).into(iv_item);
            TextView tv_price = (TextView) view.findViewById(R.id.tv_price);
            tv_price.setText(item.getPrice()+"");
//            tv_price.setText(MyUtils.getdouble(item.getPrice()));
            TextView tv_sales = (TextView) view.findViewById(R.id.tv_sales);
//            tv_sales.setText("销量：" + item.getSales());
            tv_sales.setText("销量：" + (item.getSales() + item.getRealSales()));
            TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
            tv_title.setText(item.getName());
            TextView tv_giving = (TextView) view.findViewById(R.id.tv_giving);
//            tv_giving.setText("最高抵扣" + (item.getCouponLimit() * 10) + "元");

            if (item.getCouponLimit() == 0) {
                tv_giving.setText("");
            } else {
                tv_giving.setText("最高抵扣" + (item.getCouponLimit() * 10) + "元");
            }
            return view;
        }
    }

    /**
     * 商家服务列表
     */
    class LvSbAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return listmerchant.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View view = getLayoutInflater().inflate(R.layout.lv_sb_item, null);
            MerchantItem item = listmerchant.get(position);

            TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
            tv_name.setText(item.getShortName());
            if (item.isFollowStatus()) {
                tv_name.setTextColor(getResources().getColor(R.color.text_main));
                tv_name.setTypeface(Typeface.DEFAULT_BOLD);

            } else {
                tv_name.setTypeface(Typeface.DEFAULT);
                tv_name.setTextColor(getResources().getColor(R.color.colorblack));
            }
            ImageView iv_vip = (ImageView) view.findViewById(R.id.iv_vip);
            ImageView iv_security = (ImageView) view.findViewById(R.id.iv_security);
            TextView tv_distance = (TextView) view.findViewById(R.id.tv_distance);
            double distance = item.getDistance() / 1000;
            DecimalFormat df = new DecimalFormat("0.##");
            String st = df.format(distance);
            tv_distance.setText(st + "km");
//            intiDistance(tv_distance, item);
            if (item.getVipStatus() == 1) {
                iv_vip.setVisibility(View.VISIBLE);
            } else {
                iv_vip.setVisibility(View.GONE);
            }
            if (item.getGuaranteeStatus() == 1) {
                iv_security.setVisibility(View.VISIBLE);
            } else {
                iv_security.setVisibility(View.GONE);
            }
            return view;
        }
    }

    /**
     * 距离计算
     *
     * @param
     * @param item
     */
    private void intiDistance(TextView tv, MerchantItem item) {
        LatLng startLatlng = new LatLng(StartActivity.mLatitude, StartActivity.mLongitude);
        LatLng endLatlng = new LatLng(Double.valueOf(item.getLatitude()), Double.valueOf(item.getLongitude()));

        double distance = AMapUtils.calculateLineDistance(startLatlng, endLatlng);
        distance = distance / 1000;
        DecimalFormat df = new DecimalFormat("0.##");
        String st = df.format(distance);
        tv.setText(st + "km");
    }


    @Override
    public void onResume() {
        super.onResume();
        sv_item.scrollTo(0, 0);
    }


    /**
     * 获取banner
     *
     * @param typebanner INDEX 首页、 UNION 联盟 、SHOP 商家列表 、ACTIVITY 热门活动
     */
    private void GetBanner(final String typebanner) {
        String url = API.GetBanner;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数

//        JSONObject ob = new JSONObject();
//        ob.put("type", typebanner);
        params.addFormDataPart("type", typebanner);
//        ob.put("captcha", code);
//        params.addFormDataPart("file", file);//上传单个文件
//        params.addFormDataPart("files", files);//上传多个文件
//        params.addHeader("token", token);//添加header信息
//        params.applicationJson(ob);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    listbanner.addAll(JSONObject.parseArray(datastr, BannerItem.class));
                    intiBanner();

                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            delAct(mContent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
